package org.hagopa.games.moneypool.dblayer;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.hagopa.games.moneypool.dblayer.Connector.DBConnector;


public class DBQueue implements Runnable{
	
	private DBConnector dbc = DBConnector.getInstance();
	
	private List < IDataAdopt > incomingReqs = null; 

	public DBQueue(){
		incomingReqs = Collections.synchronizedList(new LinkedList<IDataAdopt>());
		dbc.toString();
	}
	
	public List<IDataAdopt> getRef2Q(){
		return this.incomingReqs;
	}
	
//	private ResultSet loadData(String sqlrequest){
	//	Statement stmt = null;
	//	ResultSet rs = null;
		
	//	return rs;
//	}
	public void run() {
		// TODO Auto-generated method stub
		 try {
	         System.out.println("Start " 
	             + Thread.currentThread().getName());
	       
	         // you may need to wait for the first data available 
	         // with a BlockingQueue it's done for you. 
	         IDataAdopt value = incomingReqs.remove(0);
	         String sqlrequest = null;
	         while ((sqlrequest = value.getQuery()) != null) {
	            System.out.println(Thread.currentThread().getName()
	               +": " + value );
	            /*
	                do something with value
	            */    
	            ResultSet rs = null;
	            Statement stmt = null;
	            
	            try {
	 //   			stmt = DBConnector.getConn().createStatement();
	    			if(value.getQueryType().equals("proc"))
	    			{
	    				
	    				CallableStatement cs = DBConnector.getConn().prepareCall(sqlrequest);
	    				rs = (ResultSet)cs.executeQuery();
	    				//TODO: Should implement passing parameters to stored procedure
	    			}
	    			else
	    			{
	    				rs = (ResultSet)stmt.executeQuery(sqlrequest);
	    			}
	    			value.parseDBresponse(rs);
	    			rs.close();
	    			stmt.close();
	    		
	    		} catch (SQLException e) {
	    			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    			
	    		}
	            value = incomingReqs.remove(0);
	        }
	      }
	      catch (Exception e) {
	         System.out.println(Thread.currentThread().getName() 
	             + " " + e.getMessage());
	      }

	}
	
}
